using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

public class TestLoadScene : MonoBehaviour
{
    private string tempsceneId;
    private string sceneId = "6141";

    private bool isLoading;
    private Scene curscene;

    private void OnGUI()
    {

        GUILayout.BeginHorizontal();
        GUILayout.Label($"scene {sceneId}", GUILayout.Width(100));
        sceneId = GUILayout.TextField(sceneId, GUILayout.Width(100));
        GUILayout.EndHorizontal();
        if (isLoading == false && GUILayout.Button("Tp"))
        {
            _LoadScene();
        }
    }


    void _LoadScene()
    {
        StartCoroutine(__LoadScene(sceneId));
    }

    private IEnumerator __LoadScene(string id)
    {
        isLoading = true;
        // if (!string.IsNullOrEmpty(curscene.name))
        // {
        //     var w = SceneManager.UnloadSceneAsync(curscene);
        //     while (!w.isDone)
        //     {
        //         yield return 0;
        //     }
        // }

        yield return 0;
        var web = UnityWebRequestAssetBundle.GetAssetBundle(
            $"https://61.woogi.cn/client/assets_view/1/StreamingAssets/AssetBundle/WebGL/aaresourcesextends/scenebake/{id}.webgl?ran={Time.realtimeSinceStartup}");
        yield return web.SendWebRequest();
        Debug.Log("load done");
        var ab = DownloadHandlerAssetBundle.GetContent(web);
        Debug.Log($"ab scene:1");
        if (ab == null)
        {
            Debug.Log($"ab scene:null");
        }

        SceneManager.LoadScene(sceneId, LoadSceneMode.Additive);
        yield return 0;
        Debug.Log($"ab scene:2");
        isLoading = false;
        curscene = SceneManager.GetSceneByName(id);
        Debug.Log($"cur scene:{curscene.name}");
        ab.Unload(false);
        ab = null;

        Debug.Log($"Camera.main.transform is {Camera.main.transform}");
        var go = GameObject.Find("Flag_play_pos");
        if (go != null)
        {
            //Camera.main.transform.LookAt(go.transform);
            Debug.Log($"Flag_play_pos find");
            Camera.main.transform.Find("test");
            Camera.main.transform.LookAt(go.transform);
        }
        else
        {
            Debug.Log($"Flag_play_pos is null");
        }
    }
}